<script setup lang="ts">
import type { OptionsRow } from "plus-pro-components";
import { reactive, ref } from "vue";
import { message } from "@/utils/message";
import $request from "./utils/request";

// 定义事件
const emit = defineEmits(["ok"]);

// 状态参数
const state = reactive({
  // 当前编辑的ID
  id: 0,
  // 标题
  title: "",
  // 用户昵称
  nickname: "",
  // 加载中
  isLoading: false,
  // 提交中
  confirmLoading: false,
  // 是否显示
  visible: false
});

// 当前用户角色（已选）
const userRoles = ref<Id[]>();

// 完整角色数据
const fullRoles = ref<OptionsRow>([]);

// 弹窗开启
const handleOpen = async (options: FormModalOptions) => {
  state.isLoading = true;
  state.confirmLoading = false;
  if (typeof options.id === "number" && options.id) {
    state.id = options.id;
    const userData = await $request.get.detail(options.id);
    state.title = `分配 ${userData.username} 用户的角色`;
    state.nickname = userData.nickname;
    const roles = userData.roles;
    userRoles.value = roles.map(item => item.id);
    fullRoles.value = await $request.get.options({
      type: "roles",
      params: {
        page: 1,
        pageSize: 100
      }
    });
    state.visible = true;
    setTimeout(() => {
      state.isLoading = false;
    }, 0);
  } else {
    message("数据读取失败，请刷新页面后重试", { type: "error" });
  }
};

// 提交
const handleSubmit = async () => {
  try {
    state.confirmLoading = true;
    const data = {
      roles: userRoles.value
    };
    await $request.put.setRoles(state.id, data);
    message("更新成功", { type: "success" });
    emit("ok");
    state.visible = false;
  } finally {
    state.confirmLoading = false;
  }
};

defineExpose({
  handleOpen
});
</script>

<template>
  <plus-dialog
    v-model="state.visible"
    :title="state.title"
    closeOnClickModal
    cancel-text="取消"
    confirm-text="确定"
    :confirm-loading="state.confirmLoading"
    @confirm="handleSubmit"
  >
    <plus-form-item
      v-model="state.nickname"
      label="用户昵称"
      prop="nickname"
      :field-props="{
        disabled: true
      }"
    />
    <plus-form-item label="角色列表" prop="roles">
      <template #plus-field-roles>
        <el-select v-model="userRoles" multiple placeholder="请选择角色">
          <el-option
            v-for="item in fullRoles"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template>
    </plus-form-item>
  </plus-dialog>
</template>

<style lang="scss" scoped>
//
</style>
